/*
 * FightClub.java
 *
 * Created on 29 October 2006, 16:19
 */

package digitrix.fightclub.game;

import digitrix.fightclub.network.ConnectionManager;
import digitrix.fightclub.util.CustomFont;
import digitrix.network.bt.BTDispatcher;
import digitrix.network.bt.BTListener;
import digitrix.network.bt.BTManager;
import java.io.IOException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
 *
 * @author  Josh
 * @version
 */
public class FightClub extends MIDlet implements CommandListener {
    
    public static final int GAMEID = 1008;  // game identifier (for server requests etc) 
    
    private static FightClub _instance; 
    
    private static final String IMGPATH_FONT_STRIP             = "/digitrix/fightclub/res/font.png";
    private static final String IMGPATH_SMALL_FONT_STRIP       = "/digitrix/fightclub/res/font_range_small2.png"; 
    private static final String IMGPATH_DEFAULT_WALLPAPER      = "/digitrix/fightclub/res/fightclub.png";    
    private static final String IMGPATH_DEFAULT_ARROWS         = "/digitrix/fightclub/res/arrows.png";
    
    public static final int GAME_MODE_PRACTICE      = 0; 
    public static final int GAME_MODE_CHALLENGE     = 1; 
    private int _currentGameMode = -1;     
    
    private boolean _server = false;                
    
    private Command _cmdExit; 
    private Command _cmdMenu; 
    private Command _cmdLoginOK = null;
    private Command _cmdLoginCancel = null;    
    
    private Displayable _currentDisplay = null;
    private GameManager _gameManager = null;
    private MenuManager _menuManager = null;
    private TextBox _tbUsername = null;
    private TextBox _tbPassword = null;    
    
    private ConnectionManager _cxnManager = null; 
    private CustomFont _gameFont = null; 
    private boolean _hasRunningGame = false; 
    
    private Image _imgFontStrip = null; 
    private Image _imgSmallFontStrip = null; 
    private Image _imgWallpaper = null;
    private Image _imgArrows = null;
    
    // BT comm objects
    private BTManager _btManager = null;          
    
    public FightClub(){
        _instance = this;         
        _cmdExit = new Command( "Exit", Command.EXIT, 1 );  
        _cmdMenu = new Command( "Menu", Command.BACK, 2 ); 
        _cmdLoginOK = new Command( "OK", Command.OK, 1 );
        _cmdLoginCancel = new Command( "Cancel", Command.BACK, 2 );
        
        _tbUsername = new TextBox( "Enter Username", "", 20, TextField.ANY );
        _tbUsername.addCommand( _cmdLoginOK );
        _tbUsername.addCommand( _cmdLoginCancel );
        _tbUsername.setCommandListener( this );
        
        _tbPassword = new TextBox( "Enter Password", "", 20, TextField.ANY );
        _tbPassword.addCommand( _cmdLoginOK );
        _tbPassword.addCommand( _cmdLoginCancel );
        _tbPassword.setCommandListener( this );
        
        initCommon(); 
    }
    
    public static FightClub getInstance(){
        return _instance;                        
    }    
    
    public void startApp() {
        activateMenuManager(); // start game
    }
    
    public void pauseApp() {
    }
    
    public void destroyApp(boolean unconditional) {
        printDebug( "FightClub", "destoryApp", "Destroying app" );
        if( _btManager != null ){
            _btManager.close(); 
        }
        
        if( _menuManager != null )
            _menuManager.stop(); 
        
        if( _gameManager != null )
            _gameManager.stop();                                 
        
        _btManager = null;
        _menuManager = null; 
        _gameManager = null;         
        
        printDebug( "FightClub", "destoryApp", "App Destroyed - bye bye" );
    }
    
    public void exit(){
        try{
            destroyApp( true );
            notifyDestroyed(); 
        }
        catch( Exception ex ){}
    }
    
    public void activateDisplayable( IManager s ){
        try{           
            Display.getDisplay( _instance ).setCurrent( (Displayable)s ); 
        }
        catch( Exception e ){
            e.printStackTrace(); 
        }
        
        printDebug( "FightClub", "activateDisplable", "activing displayable - just about to wake it up!" ); 
        s.wakeup(); 
    }
    
    public void activateDisplayable2( Displayable s ){
        try{           
            Display.getDisplay( _instance ).setCurrent( s ); 
        }
        catch( Exception e ){
            e.printStackTrace(); 
        }               
    }
    
    public static Displayable getActivatedDisplayable(){
        return Display.getDisplay( _instance ).getCurrent();  
    }
    
    public void activateUsernameTB(){
        _currentDisplay = _tbUsername;
        activateDisplayable2( _tbUsername ); 
    }
    
    public void activatePasswordTB(){
        _currentDisplay = _tbPassword;
        activateDisplayable2( _tbPassword ); 
    }
    
    public void activateMenuManager(){
        // make the game thread sleep 
        if( _gameManager != null )
            _gameManager.sleep(); 
        
        if( _menuManager == null ){
            try{
                _menuManager = new MenuManager();
                _menuManager.addCommand( _cmdExit );                 
                _menuManager.setState( MenuManager.MENU_SPLASH );                 
            }
            catch( Exception e ){
                System.out.println( "[ERR] FightClub.activateMenuManager(1); " + e.toString() );  
                e.printStackTrace();
            }
        }                                                            
        
        if( _currentGameMode == GAME_MODE_CHALLENGE ){
            if( _hasRunningGame )
                getBTManager().dispatchNonParamEvent( BTManager.EVT_PAUSE ); 
            
            getBTManager().setCallback( _menuManager );
        }
        
        _currentDisplay = _menuManager;
        activateDisplayable( _menuManager );
    }
    
    /**
     * Either start the game or resume the game 
     **/
    public void activateGameManager( boolean newGame ){
        // make the game thread sleep 
        if( _menuManager != null )
            _menuManager.sleep(); 
        
        if( _gameManager == null ){
            try{
                _gameManager = new GameManager();
                _gameManager.addCommand( _cmdExit ); 
                _gameManager.addCommand( _cmdMenu );
                //_gameManager.setState( GameManager.GS_NEWFIGHT );                  
                //_gameManager.addCommand( _cmdExit ); 
                //_gameManager.setCommandListener( this ); 
            }
            catch( Exception e ){
                System.out.println( "[ERR] FightClub.activateGameManager(1); " + e.toString() );  
                e.printStackTrace();
            }
        }                
        
        //if( _gameManager.hasRunningGame() )
        //    _gameManager.resume();                          
        
        if( !hasPausedGame() || newGame ){
            _gameManager.setPlayerID( _menuManager.getPlayerSelected() );
            _gameManager.setOpponentID( _menuManager.getOpponentSelected() );
            _gameManager.setState( GameManager.GS_NEWFIGHT );
        }
        else{
            _gameManager.setState( GameManager.GS_RESUME );
        }
        
        
        if( _currentGameMode == GAME_MODE_CHALLENGE )
            getBTManager().setCallback( _gameManager );
        
        _currentDisplay = _gameManager;
        activateDisplayable( _gameManager );
                                         
        // set the menumanager back to displaying the main menu 
        _menuManager.setState( MenuManager.MENU_MAIN ); 
    }     

    public void commandAction(Command command, Displayable displayable) {
        if( command == _cmdExit )
            exit(); 
        else if( command == _cmdMenu ){
            _gameManager.setState( GameManager.GS_PAUSED ); 
            activateMenuManager(); 
        }
        else if( displayable == _tbUsername ){
            if( command == _cmdLoginOK )
                _menuManager.setTempUsername( _tbUsername.getString() );
            activateMenuManager();
        }
        else if( displayable == _tbPassword ){
            if( command == _cmdLoginOK )
                _menuManager.setTempPassword( _tbPassword.getString() );
            activateMenuManager();
        }
    }
    
    public boolean hasPausedGame(){
        if( _gameManager == null )
            return false;
        
        return _gameManager.getState() == GameManager.GS_PAUSED; 
    }
    
    public CustomFont getGameFont(){
        return _gameFont; 
    }
    
    public Image getWallpaper(){
        return _imgWallpaper; 
    }
    
    public Image getArrows(){
        return _imgArrows; 
    }
    
    public synchronized void ServerTalkOver(){
        _menuManager.setState( MenuManager.MENU_NETEND ); 
    }
    
    public ConnectionManager openNewConnection(){
        _cxnManager = new ConnectionManager();
        return _cxnManager; 
    }
    
    public ConnectionManager getConnectionManager(){
        return _cxnManager; 
    }
    
    public int getGameMode(){
        return _currentGameMode; 
    }
    
    public void setGameMode( int gameMode ){        
        _currentGameMode = gameMode; 
        
        if( _currentGameMode == GAME_MODE_CHALLENGE )
            getBTManager().setCallback( _menuManager ); 
    }
    
    public boolean isServer(){
        return _server; 
    }
    
    public void setServer( boolean isServer ){
        _server = isServer; 
    }      
    
    public BTManager getBTManager(){
        if( _btManager == null )
            _btManager = BTManager.getInstance(); 
        
        return _btManager;
    }    
    
    private void initCommon(){
        initWallpaper(); 
        initGameFonts(); 
        try{
            _imgArrows = Image.createImage( IMGPATH_DEFAULT_ARROWS );
        }
        catch( IOException e ){}
    }
    
    /*
     * Tile the background with this image; this could possibly be a sponsor in the
     * future
     **/
    private void initWallpaper(){
        if( _imgWallpaper == null ){
            try{
                _imgWallpaper = Image.createImage( IMGPATH_DEFAULT_WALLPAPER );
            } catch( IOException e ){}
        }
    }        
    
    private void initGameFonts(){
        try{
            _imgFontStrip = Image.createImage( IMGPATH_FONT_STRIP ); 
            _imgSmallFontStrip = Image.createImage( IMGPATH_SMALL_FONT_STRIP ); 
             
            _gameFont = new CustomFont( );
            _gameFont.initLargeFont( "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", _imgFontStrip, 13, 12, true ); 
            _gameFont.initSmallFont( "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+,-./!\"<=>? ", _imgSmallFontStrip, 8, 8, true );             
            //_gameFont.initSmallFont( "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", _imgSmallFontStrip, 8, 9, true );             
        }
        catch( IOException e ){
            System.out.println( "[ERR] FightClub.initGameFonts(1); " + e.toString() );  
        }
    }
    
    private static final boolean DEBUG = true;     
    public static void printError( String errorAt, String ex ){
        if( DEBUG ){
            if( _instance._currentGameMode == GAME_MODE_CHALLENGE ){
                String clientType = "CLIENT";
                if( _instance.isServer() ){
                    clientType = "SERVER"; 
                }
                
                System.out.println( clientType + " :: " + errorAt + " :: " + ex );
            }
            else{
                System.out.println( errorAt + " :: " + ex );
            }
        }
    }
    
    public static void printDebug( String className, String method, String msg ){
        if( DEBUG ){
            if( _instance._currentGameMode == GAME_MODE_CHALLENGE ){
                String clientType = "CLIENT";
                if( _instance.isServer() ){
                    clientType = "SERVER"; 
                }
                
                System.out.println( clientType + " :: " + className + "." + method + "() :: " + msg );
            }
            else{
                System.out.println( className + "." + method + "() :: " + msg );
            }
        }
    }
}
